/**
 * Created by guomin on 2017/5/26.
 */
var Promise = require('bluebird');
var rp = require('request-promise');
var crypto=require('crypto');
var client=require('../conf/redis');

client.on("error",function(err){
  console.log("Error",err);
});

module.exports = {
  getAccessToken: function () {
    return new Promise(function (resolve, reject) {
      client.get('access_token',function(err,access_token){
        if(err) {
          reject(err);
        }
        if(access_token){
          resolve(access_token);
        }else{
          var options={
            uri:"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxacdf06fc4ec23868&secret=a3d118a6c9f219657665cba4441a1aae",
            // uri:"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx954727bba385cd57&secret=ec8cc4ea0c48474e87d875c6302a285f",
            method:"get"
          };
          rp(options).then(function(result){
            console.log("access_token_____________",result);
            var data=JSON.parse(result);
            if(data.access_token){
              client.set("access_token",data.access_token);
              client.expire("access_token",7200);
              resolve(data.access_token);
            }else{
              reject(result);
            }
          }).catch(function(err){
            reject(err);
          });
        }
      });
    });
  },
  getJsapiTicket: function(access_token){
    return new Promise(function (resolve, reject){
      client.get('jsapi_ticket',function(err,jsapi_ticket){
        if(err){
          reject(err);
        }
        if(jsapi_ticket){
          resolve(jsapi_ticket);
        }else{
          var options={
            uri:"https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+access_token+"&type=jsapi",
            method:"get"
          };
          rp(options).then(function(jsapi_ticket){
            console.log("jsapi_ticket______________",jsapi_ticket);
            var data=JSON.parse(jsapi_ticket);
            if(data.errcode == 0){
              client.set("jsapi_ticket",data.ticket);
              client.expire("jsapi_ticket",7200);
              resolve(data.ticket);
            }else{
              reject(jsapi_ticket);
            }
          }).catch(function(err){
            reject(err);
          });
        }
      });
    });
  },
  getStringSha:function(jsapi_ticket,url){
    return new Promise(function(resolve,reject){
      var noncestr=randomWord(16);
      console.log("noncestr____________"+noncestr);
      var timestampM=Date.now();
      var timestamp=timestampM.toString().substr(0,10);
      console.log("timestamp_____________"+timestamp);
      var string="jsapi_ticket="+jsapi_ticket+"&noncestr="+noncestr+"&timestamp="+timestamp+"&url="+url;
      console.log("string_______________"+string);
      var sha1=crypto.createHash('sha1');
      sha1.update(string);
      var signature=sha1.digest('hex');
      console.log("signature_____________"+signature);
      var data={"timestamp":timestamp,"noncestr":noncestr,"signature":signature};
      resolve(data);
    });
  }

};

function randomWord(randomFlag){
  var str="";
  var arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b',
    'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
    'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z','A','B','C','D','E','F',
    'I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
  // 随机产生
  for (var i = 0; i < randomFlag; i++) {
    var pos = Math.round(Math.random() * (arr.length - 1));
    str += arr[pos];
  }
  return str;
}